package com.glasses.business.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringSystem;
import com.glasses.business.R;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.BaseActivity;
import com.glasses.business.fmanager.StackManager;
import com.glasses.business.fragment.HomeFragment;
import com.glasses.business.fragment.InfoFragment;
import com.glasses.business.fragment.MeFragment;
import com.glasses.business.utils.NotificationsUtils;
import com.nineoldandroids.view.ViewHelper;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.ToastUtil;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 作者 ： 邓勇军
 * 时间 ： 2016/12/29.
 * version:1.0
 */

public class MainActivity extends BaseActivity {

    @InjectView(R.id.tab_home)
    LinearLayout home_lay;
    @InjectView(R.id.tab_talent)
    LinearLayout sort_lay;
    @InjectView(R.id.tab_me)
    LinearLayout mine_lay;
    @InjectView(R.id.homeImg)
    ImageView homeImg;
    @InjectView(R.id.infoImg)
    ImageView infoImg;
    @InjectView(R.id.meImg)
    ImageView meImg;
    private int preId[] = {R.mipmap.icon_syl, R.mipmap.icon_zxl, R.mipmap.icon_wdl};
    private int norId[] = {R.mipmap.icon_sy, R.mipmap.icon_zx, R.mipmap.icon_wd};
    private ViewGroup Ly[];
    private boolean sessionOut = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() != null) {
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                MyApplication.getInstance().jpush = extras.getBoolean("jpush");
                sessionOut = extras.getBoolean("sessionOut", false);
                if (sessionOut) {
                    AppLog.e("==========sessionOut111===========");
                    MyApplication.getInstance().saveUser(null);
                    startActivity(new Intent(this, LoginActiviy.class));
                    finish();
                }
            }
        }
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        MyApplication.getInstance().manager = new StackManager(this);
        if (!sessionOut) {
            MyApplication.getInstance().manager.setFragment(new HomeFragment());
        }
        Ly = new ViewGroup[]{home_lay, sort_lay, mine_lay};
        if (!NotificationsUtils.isNotificationEnabled(this)) {
            new AlertDialog.Builder(this).setTitle("是否打开通知？")
                    .setMessage("当前应用通知未打开，将无法获取推送消息...(在设置界面的通知与状态栏里的通知管理即可找到该应用)")
                    .setPositiveButton("打开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            NotificationsUtils.requestPermission(MainActivity.this);
                        }
                    })
                    .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).create().show();
        }
    }

    private int position = 0;

    public void onTabClicked(View view) {
        switch (view.getId()) {
            case R.id.tab_home:
                springAnim(home_lay);
                if (position != 0) {
                    position = 0;
                    MyApplication.getInstance().manager.setFragment(new HomeFragment());
                }
                break;
            case R.id.tab_talent:
                springAnim(sort_lay);
                if (position != 1) {
                    position = 1;
                    MyApplication.getInstance().manager.setFragment(new InfoFragment());
                }
                break;
            case R.id.tab_me:
                springAnim(mine_lay);
                if (position != 2) {
                    position = 2;
                    MyApplication.getInstance().manager.setFragment(new MeFragment());
                }
                break;
            default:
                break;
        }
        setTabSelect(position);
    }

    private void springAnim(final View view) {
        SpringSystem mSpringSystem = SpringSystem.create();
        Spring spring = mSpringSystem
                .createSpring()
                .setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(250, 8))
                .addListener(new SimpleSpringListener() {
                    @Override
                    public void onSpringUpdate(Spring spring) {
                        float value = (float) spring.getCurrentValue();
                        view.setScaleX(value);
                        view.setScaleY(value);
                    }
                });
        spring.setEndValue(1);
    }

    private void setTabSelect(int position) {
        for (int i = 0; i < Ly.length; i++) {
            if (position == i) {
                ((ImageView) Ly[i].getChildAt(0)).setImageResource(preId[i]);
                ((TextView) Ly[i].getChildAt(1)).setTextColor(getResources().getColor(R.color.red));
            } else {
                ((ImageView) Ly[i].getChildAt(0)).setImageResource(norId[i]);
                ((TextView) Ly[i].getChildAt(1)).setTextColor(getResources().getColor(R.color.text_gray));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        openGPSSettings();
    }

//    private void openGPSSettings() {
//        LocationManager alm = (LocationManager) this
//                .getSystemService(Context.LOCATION_SERVICE);
//        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
//            doWork();
//            return;
//        } else {
//            Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//            startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
//        }
//
//    }
//
//    private void doWork() {
//        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//        Criteria criteria = new Criteria();
//        // 获得最好的定位效果
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        criteria.setAltitudeRequired(false);
//        criteria.setBearingRequired(false);
//        criteria.setCostAllowed(false);
//        // 使用省电模式
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
//        // 获得当前的位置提供者
//        String provider = locationManager.getBestProvider(criteria, true);
//        // 获得当前的位置
//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
//            return;
//        }
//        Location location = locationManager.getLastKnownLocation(provider);
//        if (location != null) {
//            double latitude = location.getLatitude();
//            double longitude = location.getLongitude();
//            AppLog.e("=====latitude======" + latitude + "========longitude=====" + longitude);
//        } else {
//            /**
//             * 绑定监听
//             * 参数1，设备：有GPS_PROVIDER和NETWORK_PROVIDER两种，前者是GPS,后者是GPRS以及WIFI定位
//             * 参数2，位置信息更新周期.单位是毫秒
//             * 参数3，位置变化最小距离：当位置距离变化超过此值时，将更新位置信息
//             * 参数4，监听
//             * 备注：参数2和3，如果参数3不为0，则以参数3为准；参数3为0，则通过时间来定时更新；两者为0，则随时刷新
//             */
//            locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
//        }
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0) {
//            doWork();
//        }
//    }
//
//
//    private LocationListener locationListener = new LocationListener() {
//
//        @Override
//        public void onLocationChanged(Location location) {
//            //位置信息变化时触发
//            if (location != null) {
//                AppLog.e("=====latitude111======" + location.getLatitude() + "========longitude111=====" + location.getLongitude());
//            }else{
//                ToastUtil.shortShowToast("暂未获取到位置信息...");
//            }
//        }
//
//        @Override
//        public void onStatusChanged(String provider, int status, Bundle extras) {
//            //GPS状态变化时触发
//        }
//
//        @Override
//        public void onProviderEnabled(String provider) {
//            //GPS禁用时触发
//        }
//
//        @Override
//        public void onProviderDisabled(String provider) {
//            //GPS开启时触发
//        }
//    };

}
